//
//  OAuthViewController.swift
//  XJWeiBo
//
//  Created by 徐健 on 16/3/11.
//  Copyright © 2016年 徐健. All rights reserved.
//

/*


App Key：client_id    3003452750
App Secret：client_secret   fcd6b374df6eb7ce36ed1dfc6b0c2464

授权回调页：redirect_uri      http://www.itcast.cn

*/

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        setNav()
        
        
        view.backgroundColor = UIColor.whiteColor()
        
        //加载授权页面
        loadOAuthPage()
        
        
        
        
        
        
        webView.delegate = self
        //设置不透明
        webView.opaque = false
    }
    
    
    override func loadView() {
        view = webView

        
    }
    
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func zidongdenglu(){
        let jsString = "document.getElementById('userId').value = '308594856@qq.com', document.getElementById('passwd').value = 'xujian880123' "
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    
    
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target:self, action: "close")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "私人帐户", style: .Plain, target: self, action: "zidongdenglu")
    }
    
    
    private func loadOAuthPage(){
        let urlString:String = "https://api.weibo.com/oauth2/authorize?"+"client_id=\(client_id)"+"&redirect_uri=\(redirect_uri)"
        let url:NSURL = NSURL(string: urlString)!
        
//        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
    }


}

extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        if urlString.containsString("code"){
            
            guard let query = request.URL?.query else{
                return false
            }
            
            let codeString = "code="
            
            let code = (query as NSString).substringFromIndex(codeString.characters.count)
            
            
            userAccount.onlyUserAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess{
                    SVProgressHUD.showErrorWithStatus(APPError)
                    return
                }else{
                    self.close()
                    
                    
                    //切换根控制器
//                    UIApplication.sharedApplication().keyWindow?.rootViewController = welcomeViewController()
                    
                    //发布通知
                    NSNotificationCenter.defaultCenter().postNotificationName(switchRootViewController, object: "OAuth")
                }
            })
            
            return false
        }
        return true
    }
    
    
    
}
